import { defineStore } from 'pinia'

interface UserState {
  id: string | null
  name: string | null
  avatar: string | null
  token: string | null
  isLoggedIn: boolean
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: null,
    name: null,
    avatar: null,
    token: null,
    isLoggedIn: false,
  }),
  
  actions: {
    login(userData: { id: string; name: string; avatar: string; token: string }) {
      this.id = userData.id
      this.name = userData.name
      this.avatar = userData.avatar
      this.token = userData.token
      this.isLoggedIn = true
      
      // 保存到本地存储
      localStorage.setItem('user', JSON.stringify(userData))
    },
    
    logout() {
      this.id = null
      this.name = null
      this.avatar = null
      this.token = null
      this.isLoggedIn = false
      
      // 清除本地存储
      localStorage.removeItem('user')
    },
    
    initFromStorage() {
      const storedUser = localStorage.getItem('user')
      if (storedUser) {
        try {
          const userData = JSON.parse(storedUser)
          this.login(userData)
        } catch (error) {
          console.error('Failed to parse user data from localStorage', error)
          this.logout()
        }
      }
    }
  }
})
